import aphw._aphw as impl

import aphw

class Cursor(object):
    def __init__(self, db):
        self.__cur = impl.Cursor(db._db)
        db._cursors[id(self)] = self

    def close(self):
        self.__cur.close()

    def move_first(self):
        err = impl.move_cursor(self.__cur, impl.CursorMove.FIRST)
        if err != impl.StatusCodes.SUCCESS:
            raise aphw.StatusError(
                err,
                'Error moving Cursor to first position')

    def move_last(self):
        err = impl.move_cursor(self.__cur, impl.CursorMove.LAST)
        if err != impl.StatusCodes.SUCCESS:
            raise aphw.StatusError(
                err,
                'Error moving Cursor to last position')

    def move_next(self):
        err = impl.move_cursor(self.__cur, impl.CursorMove.NEXT)        
        if err != impl.StatusCodes.SUCCESS:
            raise aphw.StatusError(
                err,
                'Error moving Cursor to next position')
        
    def move_previous(self):
        err = impl.move_cursor(self.__cur, impl.CursorMove.PREVIOUS)
        if err != impl.StatusCodes.SUCCESS:
            raise aphw.StatusError(
                err,
                'Error moving Cursor to previous position')

    def next(self):
        err = impl.move_cursor(self.__cur, impl.CursorMove.NEXT)
        if err == impl.StatusCodes.KEY_NOT_FOUND:
            raise StopIteration()
        return self

    key = property(lambda self: aphw.Key(key=self.__cur.key))
    record = property(lambda self: aphw.record.GetRecord(self.__cur.record))
    
    def __iter__(self):
        return self

    def __enter__(self):
        return self

    def __exit__(self, type, instance, traceback):
        self.close()
        return False
